package com.cly.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cly.base.contants.CacheKeysConstants;
import com.cly.dto.ResumeDto;
import com.cly.dto.ResumeInsertDto;
import com.cly.entity.*;
import com.cly.enums.PostStatusEnum;
import com.cly.mapper.ResumeMapper;
import com.cly.result.JsonRequest;
import com.cly.result.exenum.RequestException;
import com.cly.service.*;
import com.cly.vo.PostSubmitVo;
import com.cly.vo.ResumeOneVo;
import com.cly.vo.ResumeSubmitVo;
import com.cly.vo.ResumeVo;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 简历表 服务实现类
 *
 * @author by 春风能解释
 * <p>
 * 2024/11/9
 */
@Service
@RequiredArgsConstructor
public class ResumeServiceImpl extends ServiceImpl<ResumeMapper, Resume> implements IResumeService {

    /**
     * 工作经历服务
     */
    private final IWorkExperienceService workExperienceService;

    /**
     * 项目经历服务
     */
    private final IProjectExperienceService projectExperienceService;

    /**
     * 学历经历服务
     */
    private final IEducationExperienceService educationExperienceService;

    /**
     * 岗位简历服务
     */
    private final IPostResumeService postResumeService;

    /**
     * 岗位服务
     */
    private final IPostService postService;

    /**
     * 查看一个简历
     *
     * @param id ID
     * @return JSON
     */
    @Override
    @Cacheable(value = CacheKeysConstants.RecruitKeys.RESUME_ARRAY, key = "#id")
    public JsonRequest<ResumeOneVo> lookOneResume(Long id) {
        ResumeVo resume = baseMapper.lookOneResume(id);
        if (Objects.isNull(resume)) {
            return JsonRequest.error(RequestException.NOT_FOUND);
        }
        ResumeOneVo resumeOneVo = new ResumeOneVo();
        // 查询基本信息
        resumeOneVo.setResume(resume);
        // 查询教育经历
        resumeOneVo.setEducationExperiences(educationExperienceService.lookOneEducationExperience(id).getData());
        // 查询工作经历
        resumeOneVo.setWorkExperiences(workExperienceService.lookOneWorkExperience(id).getData());
        // 查询项目经历
        resumeOneVo.setProjectExperiences(projectExperienceService.lookProjectExperience(id).getData());
        return JsonRequest.success(resumeOneVo);
    }

    /**
     * 查看用户的简历列表
     *
     * @param current 页码
     * @param size    页长
     * @param userId  用户ID
     * @return JSON
     */
    @Override
    @Cacheable(value = CacheKeysConstants.RecruitKeys.RESUME_ARRAY, key = "#root.args")
    public JsonRequest<List<Resume>> lookResumeList(Integer current, Integer size, Long userId) {
        Page<Resume> resumePage = baseMapper.selectPage(
                new Page<>(current, size),
                Wrappers.lambdaQuery(Resume.class)
                        .eq(Resume::getUserId, userId));
        return JsonRequest.success(resumePage.getRecords(), resumePage.getTotal());
    }

    /**
     * 新增一个简历
     *
     * @param reservationInsertDto 简历实体
     * @return JSON
     */
    @Override
    @CacheEvict(value = CacheKeysConstants.RecruitKeys.RESUME_ARRAY, allEntries = true)
    public JsonRequest<Boolean> addOneResume(ResumeInsertDto reservationInsertDto) {
        Resume resume = reservationInsertDto.getResume();
        if (Objects.isNull(resume)) {
            return JsonRequest.error(RequestException.INSERT_ERROR);
        }
        boolean inserted = baseMapper.insertOrUpdate(resume);
        // 添加教育经历
        List<EducationExperience> educationExperiences = reservationInsertDto.getEducationExperiences();
        if (!educationExperiences.isEmpty()) {
            educationExperienceService.addOneEducationExperience(educationExperiences, resume.getId());
        }
        // 添加项目经历
        List<ProjectExperience> projectExperiences = reservationInsertDto.getProjectExperiences();
        if (!educationExperiences.isEmpty()) {
            projectExperienceService.addOneProjectExperience(projectExperiences, resume.getId());
        }
        // 添加工作经历
        List<WorkExperience> workExperiences = reservationInsertDto.getWorkExperiences();
        if (!educationExperiences.isEmpty()) {
            workExperienceService.addOneWorkExperience(workExperiences, resume.getId());
        }
        return JsonRequest.success(inserted);
    }

    /**
     * 删除一个简历
     *
     * @param id ID
     * @return JSON
     */
    @Override
    @CacheEvict(value = CacheKeysConstants.RecruitKeys.RESUME_ARRAY, allEntries = true)
    public JsonRequest<Integer> deleteResume(Long id) {
        Resume resume = getById(id);
        if (Objects.isNull(resume)) {
            return JsonRequest.error(RequestException.NOT_FOUND);
        }
        educationExperienceService.deleteEducationExperience(id);
        projectExperienceService.deleteProjectExperience(id);
        workExperienceService.deleteWorkExperience(id);
        return JsonRequest.success(baseMapper.deleteById(id));
    }

    /**
     * 修改一个简历
     *
     * @param reservationInsertDto 简历实体
     * @return JSON
     */
    @Override
    @CacheEvict(value = CacheKeysConstants.RecruitKeys.RESUME_ARRAY, allEntries = true)
    public JsonRequest<Boolean> updateResume(ResumeInsertDto reservationInsertDto) {
        Resume resume = reservationInsertDto.getResume();
        if (Objects.isNull(resume)) {
            return JsonRequest.error(RequestException.UPDATE_ERROR);
        }
        deleteResume(resume.getId());
        return addOneResume(reservationInsertDto);
    }

    /**
     * 提交简历
     *
     * @param resumeId 简历ID
     * @param postId   岗位ID
     * @return JSON
     */
    @Override
    @CacheEvict(value = {CacheKeysConstants.RecruitKeys.POST_RESUME_ARRAY, CacheKeysConstants.RecruitKeys.RESUME_POST_ARRAY}, allEntries = true)
    public JsonRequest<Boolean> submitResume(Long resumeId, Long postId) {
        boolean exists = postResumeService.exists(Wrappers.lambdaQuery(PostResume.class)
                .eq(PostResume::getPostId, postId)
                .eq(PostResume::getResumeId, resumeId));
        if (exists) {
            return JsonRequest.error(RequestException.DATA_EXISTS_BINDING);
        }
        // 查看岗位是否存在
        Post post = postService.getById(postId);
        if (Objects.isNull(post) || !post.getStatus().equals(PostStatusEnum.UNDERWAY.getValue())) {
            return JsonRequest.error(RequestException.NOT_FOUND);
        }
        return JsonRequest.success(postResumeService.saveOrUpdate(new PostResume()
                .setResumeId(resumeId)
                .setPostId(postId)));
    }

    /**
     * 查看已投递的岗位列表
     *
     * @param userId  用户ID
     * @param current 页码
     * @param size    页长
     * @return JSON
     */
    @Override
    @Cacheable(value = CacheKeysConstants.RecruitKeys.RESUME_POST_ARRAY, key = "#root.args")
    public JsonRequest<List<PostSubmitVo>> lookPostList(Integer current, Integer size, Long userId) {
        IPage<PostSubmitVo> postIPage = baseMapper.lookPostList(new Page<>(current, size), userId);
        return JsonRequest.success(postIPage.getRecords(), postIPage.getTotal());
    }

    /**
     * 查看已投递的简历列表
     *
     * @param resumeDto 条件
     * @param current   页码
     * @param size      页长
     * @return JSON
     */
    @Override
    @Cacheable(value = CacheKeysConstants.RecruitKeys.POST_RESUME_ARRAY, key = "#root.args")
    public JsonRequest<List<ResumeSubmitVo>> lookResume(Integer current, Integer size, ResumeDto resumeDto) {
        IPage<ResumeSubmitVo> submitVoIPage = baseMapper.lookResume(new Page<>(current, size), resumeDto);
        return JsonRequest.success(submitVoIPage.getRecords(), submitVoIPage.getTotal());
    }

    /**
     * 修改简历投递状态
     *
     * @param resumeDto 投递实体
     * @return JSON
     */
    @Override
    @CacheEvict(value = {CacheKeysConstants.RecruitKeys.POST_RESUME_ARRAY, CacheKeysConstants.RecruitKeys.RESUME_POST_ARRAY}, allEntries = true)
    public JsonRequest<Boolean> updateSubmitResume(ResumeDto resumeDto) {
        PostResume resume = postResumeService.getById(resumeDto.getPostResumeId());
        if (Objects.isNull(resume)) {
            return JsonRequest.error(RequestException.NOT_FOUND);
        }
        return JsonRequest.success(postResumeService.updateById((PostResume) new PostResume()
                .setInterviewTime(resumeDto.getInterviewTime())
                .setStatus(resumeDto.getStatus())
                .setId(resumeDto.getPostResumeId())));
    }
}





